package com.tsingtree.modular.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tsingtree.base.pojo.page.LayuiPageFactory;
import com.tsingtree.base.pojo.page.LayuiPageInfo;
import com.tsingtree.modular.entity.NanPopupAdvert;
import com.tsingtree.modular.entity.NanPopupAdvertItem;
import com.tsingtree.modular.mapper.NanPopupAdvertMapper;
import com.tsingtree.modular.model.params.NanPopupAdvertItemParam;
import com.tsingtree.modular.model.params.NanPopupAdvertParam;
import com.tsingtree.modular.model.result.NanPopupAdvertResult;
import com.tsingtree.modular.service.NanPopupAdvertItemService;
import com.tsingtree.modular.service.NanPopupAdvertService;
import com.tsingtree.roses.core.util.ToolUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

/**
 * <p>
 * 弹窗广告主表 服务实现类
 * </p>
 *
 * @author jagger
 * @since 2025-10-22
 */
@Service
public class NanPopupAdvertServiceImpl extends ServiceImpl<NanPopupAdvertMapper, NanPopupAdvert> implements NanPopupAdvertService {

    @Autowired
    private NanPopupAdvertItemService advertItemService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(NanPopupAdvertParam param) {
        // 1. 保存主表
        NanPopupAdvert entity = getEntity(param);
        this.save(entity);

        // 2. 如果是类型1、2或4，保存广告内容项
        if ((param.getType() == 1 || param.getType() == 2 || param.getType() == 4) && param.getItems() != null && !param.getItems().isEmpty()) {
            for (NanPopupAdvertItemParam itemParam : param.getItems()) {
                NanPopupAdvertItem item = new NanPopupAdvertItem();
                ToolUtil.copyProperties(itemParam, item);
                item.setAdvertId(entity.getId());
                advertItemService.save(item);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(NanPopupAdvertParam param) {
        // 1. 软删除主表
        NanPopupAdvert advert = this.getById(getKey(param));
        if (advert != null) {
            advert.setIsDel(true);
            this.updateById(advert);

            // 2. 软删除内容项
            List<NanPopupAdvertItem> items = advertItemService.list(
                    new QueryWrapper<NanPopupAdvertItem>()
                            .eq("advert_id", advert.getId())
                            .eq("is_del", false)
            );
            for (NanPopupAdvertItem item : items) {
                item.setIsDel(true);
                advertItemService.updateById(item);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(NanPopupAdvertParam param) {
        // 1. 更新主表
        NanPopupAdvert oldEntity = getOldEntity(param);
        NanPopupAdvert newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(oldEntity);

        // 2. 如果是类型1、2或4，重新保存广告内容项
        if (param.getType() == 1 || param.getType() == 2 || param.getType() == 4) {
            // 删除原有内容项（软删除）
            List<NanPopupAdvertItem> oldItems = advertItemService.list(
                    new QueryWrapper<NanPopupAdvertItem>()
                            .eq("advert_id", oldEntity.getId())
                            .eq("is_del", false)
            );
            for (NanPopupAdvertItem item : oldItems) {
                item.setIsDel(true);
                advertItemService.updateById(item);
            }

            // 保存新的内容项
            if (param.getItems() != null && !param.getItems().isEmpty()) {
                for (NanPopupAdvertItemParam itemParam : param.getItems()) {
                    NanPopupAdvertItem item = new NanPopupAdvertItem();
                    ToolUtil.copyProperties(itemParam, item);
                    item.setAdvertId(oldEntity.getId());
                    advertItemService.save(item);
                }
            }
        }
    }

    @Override
    public NanPopupAdvertResult findBySpec(NanPopupAdvertParam param) {
        // 1. 查询主表
        NanPopupAdvert advert = this.getById(getKey(param));
        if (advert == null) {
            return null;
        }

        NanPopupAdvertResult result = new NanPopupAdvertResult();
        ToolUtil.copyProperties(advert, result);

        // 2. 如果是类型1、2或4，查询内容项
        if (advert.getType() == 1 || advert.getType() == 2 || advert.getType() == 4) {
            List<NanPopupAdvertItem> items = advertItemService.list(
                    new QueryWrapper<NanPopupAdvertItem>()
                            .eq("advert_id", advert.getId())
                            .eq("is_del", false)
                            .orderByAsc("sort")
            );
            result.setItems(items);
        }

        return result;
    }

    @Override
    public List<NanPopupAdvertResult> findListBySpec(NanPopupAdvertParam param) {
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(NanPopupAdvertParam param) {
        Page pageContext = getPageContext();
        IPage<NanPopupAdvertResult> page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    private Serializable getKey(NanPopupAdvertParam param) {
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private NanPopupAdvert getOldEntity(NanPopupAdvertParam param) {
        return this.getById(getKey(param));
    }

    private NanPopupAdvert getEntity(NanPopupAdvertParam param) {
        NanPopupAdvert entity = new NanPopupAdvert();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}

